//  同步菜单逻辑
export async function syncSysMenu(sourceConn, targetConn, diyTable) {
  ALTER_FN(sourceConn, targetConn);
  const tableId = diyTable.Id;
  const sql = `SELECT * FROM sys_menu WHERE DiyTableId = ?`;
  console.log(`开始同步 sys_menu: ${tableId}`);
  const [sourceMenus] = await sourceConn.query(sql, [tableId]);

  if (sourceMenus.length === 0) {
    console.log(`⚠️ diy_table(${diyTable.Name}) 在源库中无 sys_menu 第一处`);
    return null;
  }

  let lastResult = [];
  for (const sourceMenu of sourceMenus) {
    // todo： 如果他有父级的菜单目录 把父级的菜单目录给同步过来
    console.log("sourceMenu.ParentId", sourceMenu.ParentId);
    if (sourceMenu.ParentId) {
      const parentMenu = await syncParentMenu(sourceConn, targetConn, {
        Id: sourceMenu.ParentId,
      });
      if (parentMenu) {
        console.log(`✅ 同步父级菜单目录: ${parentMenu.Name}`);
      }
    }
    const [targetMenus] = await targetConn.query(sql, [sourceMenu.DiyTableId]);
    // 检查目标表中是否有这些菜单记录 根据id 没有这个id 就给他插入进去
    if (!targetMenus.map((item) => item.Id).includes(sourceMenu.Id)) {
      const fields = Object.keys(sourceMenu);
      const placeholders = fields.map(() => "?").join(", ");
      const escapedFields = fields.map((f) => `\`${f}\``).join(", ");
      const values = fields.map((f) => sourceMenu[f]);

      const insertSql = `INSERT INTO sys_menu (${escapedFields}) VALUES (${placeholders})`;
      await targetConn.query(insertSql, values);
      console.log(`✅ 插入 sys_menu 记录`);
      lastResult.push(sourceMenu);
    } else {
      // 如果已经存在，则更新
      const fields = Object.keys(sourceMenu);
      const setClause = fields.map((f) => `\`${f}\` = ?`).join(", ");
      const updateSql = `UPDATE sys_menu SET ${setClause} WHERE Id = ?`;
      await targetConn.query(updateSql, [...fields.map((f) => sourceMenu[f]), sourceMenu.Id]);
      console.log(`✅ 更新 sys_menu 记录`);
      lastResult.push(sourceMenu);
    }
  }
  return lastResult;
}
//  同步菜单逻辑
async function syncParentMenu(sourceConn, targetConn, diyTable) {
  const tableId = diyTable.Id;
  console.log(`开始同步父级菜单目录: 113`, tableId);
  const sql = `SELECT * FROM sys_menu WHERE Id = ?`;
  const [sourceMenus] = await sourceConn.query(sql, [tableId]);
  // console.log("sourceMenus111", sourceMenus);
  if (sourceMenus.length === 0) {
    console.log(`⚠️ diy_table(${diyTable.Name}) 在源库中无 sys_menu 第二处`);
    return null;
  }

  const sourceMenu = sourceMenus[0];
  // 1. 补齐目标库 sys_menu 缺失字段

  console.log(`开始同步父级菜单目录: ${sourceMenu.Name}`);
  // todo： 如果他有父级的菜单目录 把父级的菜单目录给同步过来
  if (sourceMenu.ParentId) {
    const parentMenu = await syncParentMenu(sourceConn, targetConn, {
      Id: sourceMenu.ParentId,
    });
    console.log(`✅ 同步父级菜单目录: ${parentMenu ? parentMenu.Name : "无"}`);
    if (parentMenu) {
      console.log(`✅ 同步父级菜单目录: ${parentMenu.Name}`);
    }
  }
  const [targetMenus] = await targetConn.query(sql, [tableId]);
  if (targetMenus.length > 0) {
    console.log(`🔄 父级sys_menu 已存在，跳过插入`);
    return targetMenus[0];
  } else {
    const fields = Object.keys(sourceMenu);
    const placeholders = fields.map(() => "?").join(", ");
    const escapedFields = fields.map((f) => `\`${f}\``).join(", ");
    const values = fields.map((f) => sourceMenu[f]);

    const insertSql = `INSERT INTO sys_menu (${escapedFields}) VALUES (${placeholders})`;
    await targetConn.query(insertSql, values);
    console.log(`✅ 插入 父级sys_menu 记录`);

    return sourceMenu;
  }
}

async function ALTER_FN(sourceConn, targetConn) {
  // 1. 补齐目标库 sys_menu 缺失字段
  const [srcCols] = await sourceConn.query("SHOW COLUMNS FROM sys_menu");
  const [tgtCols] = await targetConn.query("SHOW COLUMNS FROM sys_menu");
  const tgtColNames = tgtCols.map((col) => col.Field);
  for (const srcCol of srcCols) {
    if (!tgtColNames.includes(srcCol.Field)) {
      const addSql = `ALTER TABLE sys_menu ADD COLUMN \`${srcCol.Field}\` ${srcCol.Type} ${srcCol.Null === "NO" ? "NOT NULL" : ""} ${
        srcCol.Default !== null ? `DEFAULT '${srcCol.Default}'` : ""
      }`;
      await targetConn.query(addSql);
      console.log(`➕ [syncSysMenu] 补充目标库 sys_menu 字段: ${srcCol.Field}`);
    }
  }
}
